package struts.xml;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class XMLFactory {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(XMLFactory.class);

	public XMLFactory() {

	}

	@SuppressWarnings("unchecked")
	public static Map<String, XMLBean> createXml(String xmlPath) {
		logger.info("********初始化xml*****");
		SAXBuilder builder = new SAXBuilder();
		Map<String, XMLBean> xmlBeanMap = new HashMap<String, XMLBean>();
		try {
			Document document = builder.build(new File(xmlPath));
			Element root = document.getRootElement();
			Element actionFormRoot = root.getChild("formbeans");
			List<Element> forms = actionFormRoot.getChildren();
			Element actionRoot = root.getChild("action-mapping");
			List<Element> actions = actionRoot.getChildren();
			for (Element element : actions) {
				XMLBean xmlBean = new XMLBean();
				String path = element.getAttributeValue("path");
				xmlBean.setPath(path);
				String form = element.getAttributeValue("form");
				for (Element el : forms) {
					if (form.equals(el.getAttributeValue("name"))) {
						String formClass = el.getAttributeValue("class");
						xmlBean.setFormClass(formClass);
						break;
					}

				}
				String type = element.getAttributeValue("type");
				xmlBean.setActionClass(type);
				Map<String, String> forward = new HashMap<String, String>();
				List<Element> forwards = element.getChildren();
				for (Element ele : forwards) {
					String name = ele.getAttributeValue("name");
					String value = ele.getAttributeValue("value");
					forward.put(name, value);
				}
				xmlBean.setForward(forward);
				logger.info(xmlBean);
				xmlBeanMap.put(path, xmlBean);
			}

		} catch (Exception e) {
			logger.info("********xml初始化错误!******");
			logger.equals(e);
		}

		return xmlBeanMap;
	}
}
